#include"../include/receive2.h"
#include"../include/data_process.h"

char myport2[10] = "9160";
int udp_fd2;
struct sockaddr_in my_addr2;
struct sockaddr_in dst_addr2;
char recv_buf2[60000];
Mat img_decode2;
Mat dst_image2;
int n_recv2;
//string str_tmp = (*recv_buf).str();
vector<uchar> data2;

//udp初始化
void init_udp2()
{
    cout<<"B节点 start work！"<<endl;
    udp_fd2 = socket(AF_INET,SOCK_DGRAM,0);
    if(udp_fd2 == -1)
    {
        perror("socket failed!");
    }
}

//初始化地址，端口
void init_my_addr2()
{
    bzero(&my_addr2,sizeof(my_addr2));
    my_addr2.sin_family = AF_INET;
    my_addr2.sin_port = htons(atoi(myport2));
    my_addr2.sin_addr.s_addr = htonl(INADDR_ANY);
}

//绑定
void bind_udp2()
{
    int opt = 1;
    setsockopt(udp_fd2,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
    if(bind(udp_fd2,(const struct sockaddr *)&my_addr2,sizeof(my_addr2)))
    {
        perror("bind failed");
    }
}

//接受数据
void receive_data2()
{
    //printf("Waitting data ~~~~~~\n");
    bzero(&dst_addr2,sizeof(dst_addr2));
    bzero(recv_buf2,sizeof(recv_buf2));
    socklen_t len = sizeof(dst_addr2);
    n_recv2 = recvfrom(udp_fd2,recv_buf2,sizeof(recv_buf2),0,(struct sockaddr *)&dst_addr2,&len);
    //cout<<"ip:"<<inet_ntoa(dst_addr2.sin_addr)<<" port:"<<ntohs(dst_addr2.sin_port)<<" bety:"<<n_recv2<<" data:"<<recv_buf2<<endl;
}

//解压数据
void chage_data2()
{
    for(auto i : recv_buf2)
    {
        data2.push_back(i);
    }
    img_decode2 = imdecode(data2,CV_LOAD_IMAGE_COLOR);
    resize(img_decode2,img_decode2,Size(640,480),0,0,INTER_AREA);
    //imshow("1",img_decode2);
    
    waitKey(10);
    /*
    if(waitKey(10)==27)
        destroyAllWindows();
        break;
    */
}

//接受端初始化集成函数
void receive_init_all2()
{
    init_udp2();
    init_my_addr2();
    bind_udp2();
}

//接受端工作集成函数
void receive_do_all2()
{
    while (1)
    {
        receive_data2();
        chage_data2();
        process2(img_decode2,dst_image2,"B节点");
        data2.clear();
    }
}